<template>
  <div class="app-container">
    <div class="filter-container" id="filter-container">
      <span v-for="column in tmpt.columnConditionList">
        <el-select
          v-if="column.columnType=='select'"
          v-model="listQuery[column.columnName]"
          :placeholder="column.columnShowName"
          class="filter-item"
          size="small"
          clearable
          style="width: 150px; margin-left: 5px; ">
          <el-option
            v-for="item in column.a1TemplateColumnOptionDtoList"
            :key="item.id"
            :label="item.name"
            :value="item.id" />
        </el-select>
        <el-date-picker
          v-else-if="column.columnType=='date-range'"
          v-model="listQuery[column.columnName]"
          type="daterange"
          value-format="yyyy-MM-dd"
          align="left"
          unlink-panels
          range-separator="至"
          :start-placeholder="column.columnShowName+':  开始'"
          end-placeholder="结束"
          :picker-options="pickerOptions"
          size="small"
          class="filter-item"
          style="width: 300px; margin-left: 5px; "
        />
        <el-input
          v-else
          v-model="listQuery[column.columnName]"
          size="small"
          clearable
          :placeholder="column.columnShowName"
          class="filter-item"
          @keyup.enter.native="handleFilter"
          style="width: 150px; margin-left: 5px; "
        />
      </span>
      <el-button :loading="queryLoading" class="filter-item" size="small" type="primary" plain icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button v-if="hasDownloadBtn" :loading="downloadLoading" class="filter-item" size="small" type="primary" plain icon="el-icon-download" @click="handleDownload">
        导出报表
      </el-button>
      <el-button v-if="hasAddBtn" class="filter-item" size="small" type="primary" plain icon="el-icon-plus" @click="handleCreate">
        添加
      </el-button>
      <el-button v-if="hasCodeBtn" class="filter-item" size="small" type="primary" icon="el-icon-setting" @click="handleShowTmptConfig">模板配置</el-button>
      <el-button v-if="hasCodeBtn" class="filter-item" size="small" type="primary" icon="el-icon-setting" @click="handleShowColumnList">列管理</el-button>
      <el-button v-if="hasCodeBtn" class="filter-item" size="small" type="primary" icon="el-icon-setting" @click="handleCreateBuildCode4Row">生成源码</el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :height="tableHeight"
      :show-header="true"
      :show-summary="showSummary"
      :summary-method="getSummaries"
      @header-dragend="headerDragend"
      @sort-change="sortChange"
    >
      <!-- 行展开，显示的详细信息 -->
      <el-table-column
        type="expand"
        align="center"
      >
        <template slot-scope="{row}">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item
              v-for="(column, i) in columnShowList"
              :label="column.columnShowName"
              :key="i"
            >
              <!-- 只有枚举是在列名后加_Str, SQL方式是通过多对一关键查询取值 -->
              <span v-if="column.columnType=='select' && column.dataResource==1">{{ row[column.columnName+'_Str'] }}</span>
              <span v-else>
                {{ row[column.columnName] }}
              </span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>

      <!--列数据-->
      <el-table-column
        v-for="(column, i) in columnHeaderShowList"
        :key="i"
        align="center"
        :label="column.columnShowName"
        :prop="column.columnName"
        :sortable="column.sortable"
        :sort-orders="['ascending', 'descending']"
        :min-width="column.columnWidth"
        :fixed="column.fixed"
      >
        <template slot-scope="{row}">
          <!-- 只有枚举是在列名后加_Str, SQL方式是通过多对一关键查询取值 -->
          <span v-if="column.columnType=='select' && column.dataResource==1">{{ row[column.columnName+'_Str'] }}</span>
          <span v-else>
            {{ row[column.columnName] }}
          </span>
        </template>
      </el-table-column>

      <!--操作Button-->
      <el-table-column v-if="hasEditBtn || hasDelBtn" fixed="right" label="操作" align="center" min-width="130">
        <template slot-scope="{row}">
          <el-button v-if="hasEditBtn" size="mini" type="primary" icon="el-icon-edit" title="编辑" style="margin-left: 0px;" @click="handleUpdate(row)"></el-button>
          <el-button v-if="hasDelBtn" size="mini" type="danger" icon="el-icon-delete" title="删除" style="margin-left: 0px;"  @click="handleDelete(row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 增加框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="150px"  style="padding:0 40px;">
        <el-form-item v-for="(column, i) in tmpt.columnCanAddList" :key="i" :label="column.columnShowName" :prop="column.columnName">
          <el-select
            v-if="column.columnType=='select'"
            v-model="temp[column.columnName]"
            clearable >
            <el-option
              v-for="item in column.a1TemplateColumnOptionDtoList"
              :key="item.id"
              :label="item.name"
              :value="item.id" />
          </el-select>
          <el-select
            v-else-if="column.columnType=='select-multi'"
            multiple
            v-model="temp[column.columnName]"
            clearable >
            <el-option
              v-for="item in column.a1TemplateColumnOptionDtoList"
              :key="item.id"
              :label="item.name"
              :value="item.id" />
          </el-select>
          <el-date-picker
              v-else-if="column.columnType=='date' || column.columnType=='date-range'"
              v-model="temp[column.columnName]"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
          </el-date-picker>
          <el-input
            v-else
            v-model="temp[column.columnName]"
            size="small"
          />

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          保存
        </el-button>
      </div>
    </el-dialog>

    <!-- 生成源码框 -->
    <el-dialog title="生成源码框" :visible.sync="dialog4GenCodeVisible">
      <GenCode ref="genCode" :keyRandom="keyRandom" :tmptId="tmpt.id" :tmptTableName="tmpt.tableName"/>
    </el-dialog>

    <!--tmpt column dialog-->
    <el-dialog :visible.sync="dialog4ColumnListVisible" :close-on-click-modal="false" title="列管理" width="95%" >
      <TmptColumnList ref="tmptColumnList" :a1templatetableId="tmpt.id" />
    </el-dialog>

    <!--tmpt config dialog-->
    <el-dialog :visible.sync="dialog4TmptConfigVisible" :close-on-click-modal="false" title="模板配置管理" >
      <TmptConfig ref="tmptConfig" :a1templatetableId="tmpt.id" />
    </el-dialog>

  </div>
</template>

<script>
import {getTemplateMapApi, fetchList, updateApi, deleteApi, createApi, updateTmptColumn} from './tmpt-preview-api'
import waves from '@/directive/waves' // waves directive
import {deleteEmptyProperty, resizeTableHeight, reorgQueryParams} from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import TmptColumnList from './tmpt-column-list'
import TmptConfig from './tmpt-config'
import GenCode from './gen-code'

export default {
  name: 'Tmpt-Preview',
  components: {Pagination, TmptColumnList, TmptConfig, GenCode},
  directives: {waves},

  props: {
    keyRandomProp: String,
    previewVisible: Boolean
  },

  data() {
      return {
          keyRandom: '',
          tmpt: { // 存储模板数据对象
              mapAll: [],
              columnList: [],
              columnCanAddList: [],
              columnConditionList: [],
              btnIdList:[],
              btnMulti:''
          },
          tableKey: 0,
          list: [],
          total: 0,
          footer: [],
          listLoading: false,
          queryLoading: false,
          downloadLoading: false,
          listQuery: {
              page: 1,
              limit: 20,
              sort: '-id',
              deleteflag: 0 // 数据库的字段名称
          },
          temp: {},
          dialogFormVisible: false,
          dialogStatus: '',
          textMap: {
              update: '编辑框',
              create: '添加框'
          },
          dialog4ColumnListVisible: false,
          dialog4TmptConfigVisible: false,
          dialog4GenCodeVisible: false, // 生成源码框
          // control table height dynamic
          tableHeight:0, // 表格高度
          filterContainerHeight: 0, // 查询容器高度
          clientHeight: 0, // 浏览器高度
          // fixed
          fixed: false,
          // show sum footer
          showSummary: false,
          pickerOptions: {
              shortcuts: [{
                  text: '最近一周',
                  onClick(picker) {
                      const end = new Date()
                      const start = new Date()
                      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                      picker.$emit('pick', [start, end])
                  }
              }, {
                  text: '最近一个月',
                  onClick(picker) {
                      const end = new Date()
                      const start = new Date()
                      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                      picker.$emit('pick', [start, end])
                  }
              }, {
                  text: '最近三个月',
                  onClick(picker) {
                      const end = new Date()
                      const start = new Date()
                      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
                      picker.$emit('pick', [start, end])
                  }
              }]
          }
      }
  },

  computed: {
    rules() {
      const rules = {}
      this.tmpt.columnCanAddList.forEach(c => {
        const cName = c.columnName
        //rules[cName] = [{ required: true, message: 'required', trigger: 'blur' }]
      })
      return rules
    },
    // 过滤只显示可显示的数据
    columnShowList() {
      return this.tmpt.columnList.filter(c => (c.isHidden === 0 || c.isHidden === 2))
    },
    // 过滤只显示可显示的数据
    columnHeaderShowList() {
      return this.tmpt.columnList.filter(c => c.isHidden === 0)
    },
    // 列名Label：下载报名
    columnShowNameList() {
      const columnShowNameList = []
      this.columnShowList.forEach( c => {
        columnShowNameList.push(c.columnShowName)
      })
      return columnShowNameList
    },
    // 列名ColumnName：下载报表
    columnNameList() {
      const columnNameList = []
      this.columnShowList.forEach( c => {
        columnNameList.push(c.columnName)
      })
      return columnNameList
    },
    // button is show
    hasAddBtn() {
      if ( this.tmpt.btnIdList.filter(id=>id===1).length!=0 ) {
        return true
      }
      return false
    },
    hasEditBtn() {
      if ( this.tmpt.btnIdList.filter(id=>id===2).length!=0 ) {
        return true
      }
      return false
    },
    hasDelBtn() {
      if ( this.tmpt.btnIdList.filter(id=>id===3).length!=0 ) {
        return true
      }
      return false
    },
    hasDownloadBtn() {
      if ( this.tmpt.btnIdList.filter(id=>id===4).length!=0 ) {
        return true
      }
      return false
    },
    hasCodeBtn() {
      if ( this.tmpt.btnIdList.filter(id=>id===5).length!=0 ) {
        return true
      }
      return false
    }
  },

  mounted () {
    this.keyRandom = this.keyRandomProp
    this.initLayout()
    this.getList()
  },

  methods: {
    initLayout() {
      if (this.keyRandom === undefined) { return }
      getTemplateMapApi({ keyRandom: this.keyRandom }).then(result => {
        this.tmpt.mapAll = result.obj
        this.tmpt.id = result.obj.templateTableId
        this.tmpt.tableName = result.obj.tableName
        this.tmpt.columnCanAddList = result.obj.columnCanAddList
        this.tmpt.columnConditionList = result.obj.conditionColumnMapList
        this.tmpt.btnIdList = result.obj.templateTable.btnIdList
        this.tmpt.btnMulti = result.obj.templateTable.btnMulti
        const columnList = result.obj.columnList

        // 默认按ID排序
        this.tmpt.columnList = columnList.map(c => {
          if (c.columnName === 'id') {
            this.$set(c, 'sortable', 'custom')
          } else {
            this.$set(c, 'sortable', false)
          }
          return c
        })
        // 浏览器、元素大小变化时，动态调整table高度
        resizeTableHeight(this)
      })
    },

    getList() {
      if (this.keyRandom === undefined) { return }
      this.queryLoading = true
      this.listLoading = true
      deleteEmptyProperty(this.listQuery)
      this.listQuery._keyRandom = this.keyRandom
      // 重组查询条件
      const params = Object.assign({}, this.listQuery)
      reorgQueryParams(params)
      // 查询
      fetchList(params).then(result => {
          if (result.success) {
              this.list = result.map.rows
              this.total = result.map.total
              // footer
              if (result.map.footer && result.map.footer.length>0) {
                  this.showSummary = true
                  this.footer = result.map.footer
              }
              this.queryLoading = false
              this.listLoading = false
              ++this.tableKey
          }
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
        if (order === 'ascending') {
            this.listQuery.sort = '+id'
        } else {
            this.listQuery.sort = '-id'
        }
        this.handleFilter()
    },
    resetTemp() {
        this.temp = {}
    },
    // SUM
    getSummaries(param) {
        if (this.footer.length == 0) {
            return []
        }
        const sums = [];
        const { columns, data } = param;
        columns.forEach((column, index) => {
            if (index === 1) {
                sums[index] = '合计';
                return;
            }
            sums[index] = this.footer[0][column.property]
        });
        return sums;
    },
    // 添加数据
    handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
        })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const param = Object.assign({}, this.temp)
          param._keyRandom = this.keyRandom
          createApi(param).then((r) => {
            this.notify(r)
            if (r.success) {
              this.handleFilter()
              this.dialogFormVisible = false
            }
          })
        }
      })
    },
    // 编辑操作 start
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      // 消除上次出现的验证信息
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const param = Object.assign({}, this.temp)
          param._keyRandom = this.keyRandom
          updateApi(param).then((r) => {
            this.notify(r)
            if (r.success) {
              this.resetTemp()
              this.dialogFormVisible = false
              this.getList()
            }
          })
        }
      })
    },

    // 删除
    handleDelete(row) {
      this.$confirm('删除后，不可恢复；确认删除吗？')
        .then(() => {
          const param = {}
          param._id = row.id
          param._keyRandom = this.keyRandom
          deleteApi(param).then((r) => {
            this.notify(r)
            if (r.success) {
              this.getList()
            }
          })
        })
        .catch(_ => {})
    },

    // download excel
    handleDownload() {
      // 重组查询条件
      const params = Object.assign({}, this.listQuery)
      params.page = 1
      params.limit = 10000000
      params._keyRandom = this.keyRandom
      // reorgQueryParams(params)
      // console.log(params)
      // 查询
      deleteEmptyProperty(params)
      this.downloadLoading = true
      fetchList(params).then(result => {
        if (result.success) {
          import('@/vendor/Export2Excel').then(excel => {
            const tHeader = this.columnShowNameList  // excel中显示的列名
            const filterVal = this.columnNameList //['id', 'name', 'createdate', 'createman'] // excel中显示哪些列，与tHeader对应
            const list = result.map.rows
            const data = this.formatJson(filterVal, list)
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: 'excel',
              autoWidth: true,
              bookType: 'xlsx'
            })
            this.downloadLoading = false
          })
        }
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },

    // 列宽监听，远程模板列存储
    headerDragend(newWidth, oldWidth, column, event) {
      const param = {}
      param.columnname = column.property
      param.columnwidth = newWidth
      param.keyRandom = this.keyRandom
      console.log(param)
      updateTmptColumn(param).then(r => {
        console.log(JSON.stringify(r))
      })
      /*const columnWidthJson = storageUtil.readObj(ColumnShowListWidthKey)
      columnWidthJson[column.property] = newWidth
      storageUtil.save(ColumnShowListWidthKey, columnWidthJson, true)
      // 实时修改全局theadOptions中的width, 不然要刷新页面才从localstorage中读取width
      theadOptions.filter(c => c.property === column.property)[0].width = newWidth*/
    },

    // show tmpt column dialog
    handleShowColumnList() {
      this.dialog4ColumnListVisible = true
      if (this.$refs['tmptColumnList']) {
        this.$refs['tmptColumnList'].getList()
      }
    },
    // show tmpt config dialog
    handleShowTmptConfig() {
      this.dialog4TmptConfigVisible = true
    },

    // 重新生成源码
    handleCreateBuildCode4Row() {
      this.dialog4GenCodeVisible = true
      /*this.$confirm('重新生成的源码，将覆盖原有源码，请备份好，再执行？')
        .then(() => {
          const data = {
            'menu1Id': this.coding_menu_id,
            '_id': this.tmpt.id,
            'pageType': 'datagrid-sourcecode',
            'menu2Name': this.tmpt.tableName,
            'keyRandom': this.keyRandom
          }
          gen2LevelMenuApi(data).then(r => {
            this.notify(r)
          })
        })
        .catch(_ => {})*/
    }

  }
}
</script>

<style>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 100px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 40%;
  }
</style>
